package com.yingpai.fitness.dvp_2_0.main.fragment.dynamic;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bumptech.glide.Glide;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.fragment.CommonFragment;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.activity.dynamic.DynamicDetailActivity;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.entity.dynamic.DynamicHotAndCityBean;
import com.yingpai.fitness.entity.wx.TokenBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.functions.Consumer;

/**
 * 动态--热门/同城模块
 */
public class HotDynamicFragment extends CommonFragment implements RadioGroup.OnCheckedChangeListener, AdapterView.OnItemClickListener, OnRefreshLoadMoreListener {

    @BindView(R.id.new_rb)
    RadioButton new_rb;
    @BindView(R.id.hot_rb)
    RadioButton hot_rb;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.xgrid)
    GridView xgrid;
    @BindView(R.id.hot_child_rg)
    RadioGroup hot_child_rg;
    @BindView(R.id.title_bar)
    RelativeLayout title_bar;
    @BindView(R.id.empty)
    LinearLayout empty;
    private Unbinder unbinder;
    private TokenBean token;
    private int flag = 1;//
    private int orderBy = 2;
    private int pageNum = 1;
    private int pageSize = 10;
    private String city;

    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Bundle bundle = new Bundle();
        bundle.putInt("id", adapter.getItem(position).getId());
        bundle.putInt("isPraised", adapter.getItem(position).getIsPraised());
        startActivity(DynamicDetailActivity.class, bundle);
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取地址相关的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            city = location.getCity();//获取城市

            initData();

            if (flag == 3) {
                mLocationClient.stop();
            }
        }
    }

    private void initLocation() {

        mLocationClient = new LocationClient(context);
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        LocationClientOption option = new LocationClientOption();

        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；

        option.setIsNeedAddress(true);
        //是否需要地址信息 默认不需要

        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认gcj02
        //gcj02：国测局坐标；
        //bd09ll：百度经纬度坐标；
        //bd09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回wgs84类型坐标

        option.setScanSpan(0);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true

        option.setLocationNotify(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前WiFi是否超出有效期，若超出有效期，会先重新扫描WiFi，然后定位

        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明
    }

    public static HotDynamicFragment getInstance(int i) {
        HotDynamicFragment fragment = new HotDynamicFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("flag", i);

        fragment.setArguments(bundle);
        return fragment;
    }

    private QuickAdapter<DynamicHotAndCityBean.MapData.PageInfoData.ListData> adapter;

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dvp_2_0_hotwithcitydynameic, container, false);
        unbinder = ButterKnife.bind(this, view);
        title_bar.setVisibility(View.GONE);
        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));
        hot_child_rg.setOnCheckedChangeListener(this);
        EventBus.getDefault().register(this);
        token = (TokenBean) SharedPreferencesHelp.getBean(Constant.TOKENBEAN);
        flag = getArguments().getInt("flag");

        if (flag == 3) {
            if (!rxPermissions.isGranted(Manifest.permission.ACCESS_FINE_LOCATION)) {
                rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION).subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            initLocation();
                            mLocationClient.start();//重新定位
                        } else {
                            showToast("拒绝权限可能导致部分功能不能使用");
                        }
                    }
                });
            } else {
                initLocation();
                mLocationClient.start();//重新定位
            }
        }

        adapter = new QuickAdapter<DynamicHotAndCityBean.MapData.PageInfoData.ListData>(context, R.layout.dynamic_hot_city_list_item) {
            @Override
            protected void convert(BaseAdapterHelper helper, DynamicHotAndCityBean.MapData.PageInfoData.ListData item) {
                ImageView dynamic_hot_city_iv = helper.getView(R.id.dynamic_hot_city_iv);//图片
                Glide.with(context)
                        .load(item.getPhotoUrls())
                        .placeholder(R.mipmap.default_small_bg)
                        .error(R.mipmap.default_small_bg)
                        .into(dynamic_hot_city_iv);

                TextView topic_item_title = helper.getView(R.id.topic_item_title);//标题
                topic_item_title.setText(item.getThemeTitle());

                CircleImageView dynamic_hot_city_user_head_iv = helper.getView(R.id.dynamic_hot_city_user_head_iv);//某人头像

                Glide.with(context)
                        .load(item.getPublisherPhotoUrl())
                        .error(R.mipmap.default_small_bg)
                        .into(dynamic_hot_city_user_head_iv);

                TextView topic_user_head_name = helper.getView(R.id.topic_user_head_name);
                topic_user_head_name.setText(item.getPublisherName());

                TextView topic_user_collect_count_tv = helper.getView(R.id.topic_user_collect_count_tv);
                topic_user_collect_count_tv.setText(item.getPraiseNo() + "");

                ImageView dynamic_hot_city_user_collect_iv = helper.getView(R.id.dynamic_hot_city_user_collect_iv);
                if (item.getIsPraised() == 0) {
                    dynamic_hot_city_user_collect_iv.setImageResource(R.mipmap.bbs_like_no);
                } else {
                    dynamic_hot_city_user_collect_iv.setImageResource(R.mipmap.bbs_like);
                }
            }
        };
        xgrid.setAdapter(adapter);
        xgrid.setOnItemClickListener(this);

        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        unbinder.unbind();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(String messageEvent) {
        if ("点赞成功".equals(messageEvent)) {
            pageNum = 1;
            initData();
        } else if ("dynamic_success".equals(messageEvent)) {
            pageNum = 1;
            initData();
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    @OnClick({R.id.empty})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.empty:
                onRefresh(refreshLayout);
                break;
        }
    }

    @Override
    protected void initData() {
        showDialog(context,null);
        /**
         * source   根据热门，同城分类，热门传1，同城传3
         * orderBy  排序分类,不传或者传1按热度排序，按时间排序传2
         * pageNum  分页用的第几页，默认值8
         * pageSize 分页用的每页几条数据，默认值1
         */
        HttpParams httpParams = new HttpParams();
        httpParams.put("customerId", token.getId());
        if (flag == 3) {
            httpParams.put("publishCity", city);
        }
        httpParams.put("source", flag);
        httpParams.put("orderBy", orderBy);
        httpParams.put("pageNum", pageNum++);
        httpParams.put("pageSize", pageSize);
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.GET_DYNAMIC_LIST, httpParams, Url.GET_DYNAMIC_LIST,
                new Callback<DynamicHotAndCityBean>() {
                    @Override
                    public void onSuccess(DynamicHotAndCityBean bean) {
                        if (Constant.REQUEST_SUCCESS.equals(bean.getResult())) {
                            if (pageNum - 1 == 1) {
                                if(bean.getMap().getPageInfo().getTotal()>0){
                                    empty.setVisibility(View.GONE);
                                    adapter.clear();
                                    adapter.addAll(bean.getMap().getPageInfo().getList());
                                }else{
                                    empty.setVisibility(View.VISIBLE);
                                }
                            } else {
                                adapter.addAll(bean.getMap().getPageInfo().getList());
                            }
                            refreshLayout.finishRefresh();
                            refreshLayout.finishLoadMore();
                            adapter.notifyDataSetChanged();

                            int pagecount;
                            if (bean.getMap().getPageInfo().getTotal() % pageSize == 0) {
                                pagecount = bean.getMap().getPageInfo().getTotal() / pageSize;
                            } else {
                                pagecount = bean.getMap().getPageInfo().getTotal() / pageSize + 1;
                            }

                            if (pageNum > pagecount) {
                                refreshLayout.finishLoadMoreWithNoMoreData();
                            } else {
                                refreshLayout.setNoMoreData(false);
                            }
                        } else {
                            if (pageNum - 1 == 1) {
                                empty.setVisibility(View.VISIBLE);
                            }else{
                                empty.setVisibility(View.GONE);
                            }
                            showToast(bean.getMsg());
                        }
                        dismissDialog();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDialog();
                        if (pageNum - 1 == 1) {
                            empty.setVisibility(View.VISIBLE);
                        }else{
                            empty.setVisibility(View.GONE);
                        }
                    }
                });
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNum = 1;
        initData();
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        initData();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.new_rb:
                orderBy = 1;
                break;
            case R.id.hot_rb:
                orderBy = 2;
                break;
        }
        pageNum = 1;
        initData();
    }


}
